package com.lcq.demo.service;

import com.lcq.demo.common.converter.UserConverter;
import com.lcq.demo.common.enums.QueueEnum;
import com.lcq.demo.common.utils.RedisUtil;
import com.lcq.demo.entity.dto.UserDTO;
import com.lcq.demo.entity.po.User;
import com.lcq.demo.repository.UserRepository;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @author 240701005
 */
@Service
public class UserService {

    private static final String CODE_SUFFIX = "verifyCode";

    private final static String CODE_SEPARATOR = ":";

    @Resource
    private UserRepository userRepository;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SqsClient sqsClient;

    /**
     * 用户注册
     */
    public Boolean register(UserDTO userDTO) throws Exception {
        if (!userDTO.getPassword().equals(userDTO.getPassword2())) {
            throw new Exception("两次密码不一致！");
        }
        userDTO.setCreateTime(new Date(System.currentTimeMillis()));
        User user = UserConverter.INSTANCE.convertDtoToPo(userDTO);
        String verifyCode = redisUtil.get(redisUtil.buildKey(userDTO.getEmail(), CODE_SUFFIX));
        if (verifyCode.equals(userDTO.getVerifyCode())) {
            if (userRepository.findByEmail(user.getEmail()) == null) {
                userRepository.save(user);
                return true;
            }
        }
        return false;
    }

    /**
     * 发送验证码
     */
    public String sendEmail(String email) {
        String code = buildVerifyCode();
        SendMessageRequest request = SendMessageRequest.builder()
                .queueUrl(QueueEnum.TEST_QUEUE_URL.url)
                .messageBody(email + CODE_SEPARATOR + code)
//                .delaySeconds()
                .build();
        sqsClient.sendMessage(request);
        return code;
    }

    private String buildVerifyCode() {
        Random random = new Random();
        int code = random.nextInt(899999) + 100000;
        return String.valueOf(code);
    }

    public User login(UserDTO userDTO) {
        User user = userRepository.findByEmail(userDTO.getEmail());
        if (user.getPassword().equals(userDTO.getPassword())) {
            return user;
        }
        return null;
    }
}
